package com.ytjj.qmyx.mall.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.FileItem;
import com.alipay.api.domain.ReplyRecordResponse;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.dto.mqdto.SmsDto;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.DateTimeUtil;
import com.ytjj.qmyx.mall.enums.AliPayComplaintsStatusEnums;
import com.ytjj.qmyx.mall.mapper.AlipayComplaintsRecordsMapper;
import com.ytjj.qmyx.mall.mapper.ComplaintsErrorRecordsMapper;
import com.ytjj.qmyx.mall.mapper.OrdersInfoMapper;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.service.AliPayComplaintsService;
import com.ytjj.qmyx.mall.service.ComplaintsService;
import com.ytjj.qmyx.mall.utils.AlipayFactoryUtils;
import com.ytjj.qmyx.mall.utils.Base64Util;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Base64;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author EDY
 */
@Slf4j
@Service
@RefreshScope
public class AliPayComplaintsServiceImpl  implements AliPayComplaintsService {
    @Resource
    private AlipayComplaintsRecordsMapper alipayComplaintsRecordsMapper;
    @Resource
    private AlipayFactoryUtils alipayFactory;
    @Resource
    private ComplaintsErrorRecordsMapper complaintsErrorRecordsMapper;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private OrdersInfoMapper ordersInfoMapper;
    @Resource
    private ComplaintsService complaintsService;
    /**
     * 投诉单自动回复内容
     */
    @Value("${auto.reply.content:您的投诉已由我们商城客服受理，后续将通过电话/微信处理您的问题，您也可以主动拨打我们的官方客服热线0000001706联系我们（上班时间: 9:00-12:00,13:30-18:30)，我们将竭诚为您服务}")
    private String autoReplyContent;
    @Value("${auto.reply.content2:您反馈的问题已记录，后续会有商城客服专员电话或微信联系您，请您务必保持通讯畅通，以便及时处理您的问题！您也可以在商城上班时间段（9:00-12:00，13:45-18:30）主动拨打客服热线0000001727，我们一定会竭诚为您服务！}")
    private String autoReplyContent2;

    @Override
    public String uploadAliPayComplaintsImage(String image,String complainEventId) {
        String imageId = joptsimple.internal.Strings.EMPTY;
        try{
            String childId = alipayComplaintsRecordsMapper.queryChildId(complainEventId);
            AlipayClient alipayClient = alipayFactory.getAlipayClient(childId);
            String imageBase64 = Base64Util.imageUrlToBase64(image);
            FileItem fileContent = new FileItem("fileContent.jpg", Base64.getDecoder().decode(imageBase64));
            AlipayMerchantImageUploadRequest request = new AlipayMerchantImageUploadRequest();
            request.setImageType("jpg");
            request.setImageContent(fileContent);
            AlipayMerchantImageUploadResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                imageId = response.getImageId();
            }
        }catch (Exception e) {
            log.error("上传处理图片到支付宝失败! 原因:{}",e.getMessage());
            throw  new ApiException("上传处理图片到支付宝失败!");
        }
        return imageId;
    }

    @Override
    public AlipayMerchantTradecomplainQueryResponse queryAliPayComplaintsDetail(String complainEventId,String childId) throws Exception {
        try{
            AlipayClient alipayClient = getAliPayClient(childId, complainEventId);
            AlipayMerchantTradecomplainQueryRequest request= new AlipayMerchantTradecomplainQueryRequest() ;
            JSONObject bizContent = new JSONObject();
            bizContent.put("complain_event_id",complainEventId);
            request.setBizContent(bizContent.toString());
            AlipayMerchantTradecomplainQueryResponse response = alipayClient.execute(request);
            return response;
        }catch (Exception e) {
            log.error("查询支付宝投诉详情失败! 原因:{}",e.getMessage());
            throw  new ApiException("查询支付宝投诉详情失败!");
        }
    }

    @Override
    public AlipayMerchantTradecomplainReplySubmitResponse complaintsReplySubmit(AliPayComplatintsReplyRequest replyRequest) {
        try {
            AlipayClient alipayClient = getAliPayClient(replyRequest.getChildId(), replyRequest.getComplainEventId());

            AlipayMerchantTradecomplainReplySubmitRequest  request= new AlipayMerchantTradecomplainReplySubmitRequest() ;
            JSONObject bizContent = new JSONObject();
            bizContent.put("complain_event_id",replyRequest.getComplainEventId());
            bizContent.put("reply_content",replyRequest.getReplyContent());
            if (!CollectionUtils.isEmpty(replyRequest.getReplyImages())) {
                String reply_images = replyRequest.getReplyImages().stream().collect(Collectors.joining(","));
                bizContent.put("reply_images",reply_images);
            }

            request.setBizContent(bizContent.toString());
            AlipayMerchantTradecomplainReplySubmitResponse response = alipayClient.execute(request);
            //发送投诉回复短信
            sendReplyMsg(replyRequest.getComplainEventId(),null,replyRequest.getReplyContent());
            return response;
        }catch (Exception e) {
            log.error("支付宝投诉商家留言回复失败! 原因:{}",e.getMessage());
            throw  new ApiException("支付宝投诉商家留言回复失败!");
        }
    }

    private AlipayClient getAliPayClient(String childId, String complainEventId) {
        if (StringUtils.isBlank(childId)) {
            AlipayComplaintsRecords alipayComplaintsRecords = alipayComplaintsRecordsMapper.queryByComplainEventId(complainEventId);
            childId = alipayComplaintsRecords.getChildId();
            if (StringUtils.isBlank(alipayComplaintsRecords.getChildId())) {
                childId = alipayComplaintsRecordsMapper.queryChildId(complainEventId);
            }
        }
        return alipayFactory.getAlipayClient(childId);
    }

    private  void sendReplyMsg(String complainEventId,String phone,String content){
        AliPayComplaintsListResponse response = alipayComplaintsRecordsMapper.queryAliPayComplaints(complainEventId);
        if (StringUtils.isBlank(phone)) {
            phone = response.getPhoneNo();
        }
        complaintsService.sendComplaintsMsg(phone, content, response.getUserPhone());
    }


    @Override
    public AlipayMerchantTradecomplainFeedbackSubmitResponse complaintsFeedbackSubmit(AliPayComplatintsFeedbackRequest feedbackRequest) {
        try{
            AlipayClient aliPayClient = getAliPayClient(feedbackRequest.getChildId(), feedbackRequest.getComplainEventId());
            AlipayMerchantTradecomplainFeedbackSubmitRequest request= new AlipayMerchantTradecomplainFeedbackSubmitRequest() ;
            request.setComplainEventId(feedbackRequest.getComplainEventId());
            request.setFeedbackCode(feedbackRequest.getFeedbackCode());
            request.setFeedbackContent(feedbackRequest.getFeedbackContent());
            if (!CollectionUtils.isEmpty(feedbackRequest.getFeedbackImages())) {
                String feedbackImages = feedbackRequest.getFeedbackImages().stream().collect(Collectors.joining(","));
                request.setFeedbackImages(feedbackImages);
            }
            if (StringUtils.isNotBlank(feedbackRequest.getAdminName())) {
                request.setOperator(feedbackRequest.getAdminName());
            }

            AlipayMerchantTradecomplainFeedbackSubmitResponse response = aliPayClient.execute(request);
            return response;
        }catch (Exception e) {
            log.error("支付宝处理交易投诉失败! 原因:{}",e.getMessage());
            throw  new ApiException("支付宝处理交易投诉失败!");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String complaintsCallBack(Map<String, String> params,String childId) {
        try{
            // 调用SDK验证签名
//            boolean signVerified ;
//            //支付宝小程序回调
//            if (StringUtils.isNotBlank(childId) && "1".equals(childId)) {
//                signVerified = AlipaySignature.rsaCheckV1(params, alipayConstants.getCHILD_JSAPI_ALIPAY_PUBLIC_KEY(), "utf-8", "RSA2");
//            } else if (StringUtils.isNotBlank(childId) && "APP_1".equals(childId)) {
//                signVerified = AlipaySignature.rsaCheckV1(params, alipayConstants.getAPP_ALIPAY_PUBLIC_KEY(), alipayConstants.getCHARSET(), alipayConstants.getSIGNTYPE());
//            } else {
//                signVerified = AlipaySignature.rsaCheckV1(params, alipayConstants.getJSAPI_ALIPAY_PUBLIC_KEY(), "utf-8", "RSA2");
//            }
//
//            if (signVerified) {
            String biz_content = params.get("biz_content");
            Map<String,String> map = JSON.parseObject(biz_content, Map.class);
            String complain_event_id = map.get("complain_event_id");
            log.info("支付宝投诉回调通知参数complain_event_id:{},childId:{}",complain_event_id,childId);
            RLock lock = redissonClient.getLock("ALIPAY_COMPLAIN_LOCK_" + complain_event_id);
            boolean b = false;
            try {
                b = lock.tryLock(0, 60, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                lock.unlock();
            }
            if(b) {
                AlipayMerchantTradecomplainQueryResponse queryResponse = queryAliPayComplaintsDetail(complain_event_id,childId);
                if (null != queryResponse) {
                    AlipayComplaintsRecords alipayComplaintsRecords = alipayComplaintsRecordsMapper.queryByComplainEventId(complain_event_id);
                    if (ObjectUtil.isNull(alipayComplaintsRecords)) {
                        alipayComplaintsRecords  = new AlipayComplaintsRecords();
                        ComplaintsOrderResponse complaintsOrderResponse = ordersInfoMapper.queryPlatformData(queryResponse.getMerchantOrderNo());
                        if (ObjectUtil.isNotNull(complaintsOrderResponse)) {
                            String domain_url = StringUtils.isNotBlank(complaintsOrderResponse.getDomainUrl()) ? "_非支付宝" : "_支付宝渠道";
                            alipayComplaintsRecords.setPlatformData(complaintsOrderResponse.getOrderSource() + domain_url);
                            alipayComplaintsRecords.setSupplyProductId(complaintsOrderResponse.getSupplyProductId() != null ? complaintsOrderResponse.getSupplyProductId(): null);
                        }
                        alipayComplaintsRecords.setTargetId(queryResponse.getTargetId());
                        alipayComplaintsRecords.setTargetType(queryResponse.getTargetType());
                        alipayComplaintsRecords.setComplainEventId(queryResponse.getComplainEventId());
                        alipayComplaintsRecords.setStatus(queryResponse.getStatus());
                        alipayComplaintsRecords.setTradeNo(queryResponse.getTradeNo());
                        alipayComplaintsRecords.setMerchantOrderNo(queryResponse.getMerchantOrderNo());
                        alipayComplaintsRecords.setLeafCategoryName(queryResponse.getLeafCategoryName());
                        alipayComplaintsRecords.setComplainReason(queryResponse.getComplainReason());
                        alipayComplaintsRecords.setContent(queryResponse.getContent());
                        if (!CollectionUtils.isEmpty(queryResponse.getImages())) {
                            alipayComplaintsRecords.setImages(queryResponse.getImages().stream().collect(Collectors.joining(",")));
                        }

                        alipayComplaintsRecords.setPhoneNo(queryResponse.getPhoneNo());
                        alipayComplaintsRecords.setTradeAmount(new BigDecimal(queryResponse.getTradeAmount()));
                        alipayComplaintsRecords.setGmtCreate(queryResponse.getGmtCreate() == null ? null : DateTimeUtil.StrToTime(queryResponse.getGmtCreate()));
                        alipayComplaintsRecords.setGmtModified(queryResponse.getGmtModified() == null ? null : DateTimeUtil.StrToTime(queryResponse.getGmtModified()));
                        alipayComplaintsRecords.setGmtFinished(queryResponse.getGmtFinished() == null ?  null : DateTimeUtil.StrToTime(queryResponse.getGmtFinished()));
                        alipayComplaintsRecords.setChildId(childId);
                        alipayComplaintsRecordsMapper.insertSelective(alipayComplaintsRecords);
                        try{
                            log.info("支付宝投诉是否自动回复complain_event_id:{},status:{}",complain_event_id,queryResponse.getStatus());
                            if (AliPayComplaintsStatusEnums.isAutoReply(queryResponse.getStatus())) {
                                //自动回复
                                AliPayComplatintsReplyRequest replyRequest = new AliPayComplatintsReplyRequest();
                                replyRequest.setAdminId(1);
                                replyRequest.setComplainEventId(complain_event_id);
                                replyRequest.setReplyContent(autoReplyContent);
                                replyRequest.setChildId(childId);
                                AlipayMerchantTradecomplainReplySubmitResponse submitResponse = complaintsReplySubmit(replyRequest);
                                //自动回复失败
                                if (!"10000".equals(submitResponse.getCode())) {
                                    saveComplaintsErrorRecord(complain_event_id, queryResponse,autoReplyContent);
                                }
                            }

                        }catch (Exception e) {
                            log.info("自动回复失败:{}",e.getMessage());
                            saveComplaintsErrorRecord(complain_event_id, queryResponse,autoReplyContent);
                        }



                    } else {
                        alipayComplaintsRecords.setStatus(queryResponse.getStatus());
                        alipayComplaintsRecords.setGmtCreate(queryResponse.getGmtCreate() == null ? null : DateTimeUtil.StrToTime(queryResponse.getGmtCreate()));
                        alipayComplaintsRecords.setGmtModified(queryResponse.getGmtModified() == null ? null : DateTimeUtil.StrToTime(queryResponse.getGmtModified()));
                        alipayComplaintsRecords.setGmtFinished(queryResponse.getGmtFinished() == null ? null : DateTimeUtil.StrToTime(queryResponse.getGmtFinished()));
                        alipayComplaintsRecords.setChildId(childId);
                        alipayComplaintsRecordsMapper.updateByPrimaryKey(alipayComplaintsRecords);

                        try{
                            //自动回复
                            ReplyRecordResponse replyRecordResponse = queryResponse.getReplyDetailInfos().get(0);
                            String replierRole = ObjectUtil.isNotNull(replyRecordResponse) ? replyRecordResponse.getReplierRole() : "";
                            if (AliPayComplaintsStatusEnums.isAutoReply(queryResponse.getStatus()) && "USER".equals(replierRole)) {
                                AliPayComplatintsReplyRequest replyRequest = new AliPayComplatintsReplyRequest();
                                replyRequest.setAdminId(1);
                                replyRequest.setComplainEventId(complain_event_id);
                                replyRequest.setReplyContent(autoReplyContent2);
                                replyRequest.setChildId(childId);
                                AlipayMerchantTradecomplainReplySubmitResponse submitResponse = complaintsReplySubmit(replyRequest);
                                //自动回复失败
                                if (!"10000".equals(submitResponse.getCode())) {
                                    saveComplaintsErrorRecord(complain_event_id, queryResponse,autoReplyContent2);
                                }
                            }

                        }catch (Exception e) {
                            log.info("自动回复失败:{}",e.getMessage());
                            saveComplaintsErrorRecord(complain_event_id, queryResponse,autoReplyContent2);
                        }


                    }

//                    }
                    return "success";
                }
                lock.unlock();
            }
            log.info("支付宝投诉回调签名认证失败，signVerified=false, paramsJson:{}", JSON.toJSONString(params));
            return "fail";

        }catch (Exception e) {
            log.error("支付宝投诉回调错误:{}",e.getMessage());
        }
        return "fail";
    }

    private void saveComplaintsErrorRecord(String complain_event_id, AlipayMerchantTradecomplainQueryResponse queryResponse,String autoReplyContent) {
        ComplaintsErrorRecords complaintsErrorRecords = new ComplaintsErrorRecords();
        complaintsErrorRecords.setComplaintId(complain_event_id);
        complaintsErrorRecords.setCreateTime(new Date());
        complaintsErrorRecords.setStatus(1);
        complaintsErrorRecords.setOutTradeNo(queryResponse.getTradeNo());
        complaintsErrorRecords.setType(1);
        complaintsErrorRecords.setReplyContent(autoReplyContent);
        complaintsErrorRecordsMapper.insert(complaintsErrorRecords);
    }

    @Override
    public AlipayMerchantTradecomplainSupplementSubmitResponse complaintsSupplementSubmit(AliPayComplatintsSupplementRequest supplementRequest) {
        try{
            AlipayClient aliPayClient = getAliPayClient(supplementRequest.getChildId(), supplementRequest.getComplainEventId());
            AlipayMerchantTradecomplainSupplementSubmitRequest  request= new AlipayMerchantTradecomplainSupplementSubmitRequest () ;

            JSONObject bizContent = new JSONObject();
            bizContent.put("complain_event_id",supplementRequest.getComplainEventId());
            if (StringUtils.isNotBlank(supplementRequest.getSupplementContent())) {
                bizContent.put("supplement_content",supplementRequest.getSupplementContent());
            }

            if (!CollectionUtils.isEmpty(supplementRequest.getSupplementImages())) {
                String reply_images = supplementRequest.getSupplementImages().stream().collect(Collectors.joining(","));
                bizContent.put("supplement_images",reply_images);
            }

            request.setBizContent(bizContent.toString());
            AlipayMerchantTradecomplainSupplementSubmitResponse response = aliPayClient.execute(request);
            return response;
        }catch (Exception e) {
            log.error("支付宝投诉商家补充凭证失败! 原因:{}",e.getMessage());
            throw  new ApiException("支付宝投诉商家补充凭证失败!");
        }
    }

}
